<template>
  <div class="details_box">
    <NavBar :title="'提交订单'" :isLeftBtn="false" />
    <van-contact-card
      v-if="JSON.stringify(siteItem) == '{}' || !siteItem"
      type="add"
      @click="onAdd"
      add-text="选择收货地址"
    />
    <div
      v-else
      @click="handSeleSite"
      class="van-cell van-cell--center van-cell--clickable van-cell--borderless van-contact-card van-contact-card--add"
    >
      <div class="site_list">
        <div class="site_item">
          <div>
            <van-tag
              v-if="siteItem.defaultFlag === 1"
              type="danger"
              style="margin-right: 6px"
              >默认</van-tag
            >{{ siteItem.cityName }}{{ siteItem.provinceName
            }}{{ siteItem.regionName }}
          </div>
          <div class="site_title">
            {{ siteItem.cityName }}{{ siteItem.provinceName
            }}{{ siteItem.regionName }} {{ siteItem.detailAddress }}
          </div>
          <div class="site_name">
            {{ siteItem.userName }} {{ siteItem.userPhone }}
          </div>
        </div>
        <van-icon name="arrow" />
      </div>
    </div>
    <van-card
      v-for="item in list"
      :key="item.goodsId"
      :num="item.goodsCount"
      tag="爆款"
      :price="item.sellingPrice"
      desc="没那么多字段了!!"
      :title="item.goodsName"
      :thumb="$filters.prefix(item.goodsCoverImg)"
      :origin-price="item.sellingPrice"
    />
    <div style="height: 120px"></div>
    <van-submit-bar
      :loading="btnLoading"
      :price="allCount"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <template #tip><span>别墨迹,赶紧给钱</span></template>
    </van-submit-bar>
    <van-popup
      v-model:show="show"
      closeable
      position="bottom"
      @close="popupClose"
      :style="{ height: '30%' }"
    >
      <div class="play_title">给钱</div>
      <div class="play_type">
        <van-button
          @click="handPlay(1)"
          style="margin-bottom: 10px"
          color="#1989fa"
          type="primary"
          >支付宝支付</van-button
        >
        <van-button @click="handPlay(2)" color="#4fc08d" type="primary"
          >微信支付</van-button
        >
      </div>
    </van-popup>
  </div>
</template>
<script lang="ts">
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { getCart } from "@/utils/apis/cart";
import { createOrder, payOrder } from "@/utils/apis/order";
import { getAddressList } from "@/utils/apis/address";
import NavBar from "@/components/NavBar.vue";
import { Toast } from "vant";
import { Goods } from "@/utils/types/goods";
import { Site } from "@/utils/types/site";
export default defineComponent({
  name: "statement",
  components: { NavBar },
  setup() {
    const router = useRouter();
    const state = reactive({
      list: [],
      allCount: 0,
      btnLoading: false,
      siteItem: {} as Site | object,
      defaultFlag: false,
      show: false,
      orderNo: -1,
    });
    //判断是i订单点进来的还是个人中心
    //获取商品
    const init = async () => {
      const res = await getCart();
      res.data.forEach((item: Goods) => {
        item.isChecked = false;
      });
      state.list = res.data;
    };
    //选择地址
    const handSeleSite = () => {
      console.log((state.siteItem as Site).addressId);
      state.siteItem = {};
      router.push({
        path: "/site",
        query: {
          addressId: (state.siteItem as Site).addressId,
        },
      });
    };
    const getSiteItem = async () => {
      const route = useRoute();
      const { addressItem }: any = route.query;
      if (!addressItem) {
        const res = await getAddressList({ pageNumber: 100, pageSize: 1 });
        //查找是否有默认地址
        if (res.data.length === 0) {
          return;
        }
        state.defaultFlag = res.data.some((item: any) => {
          return item.defaultFlag === 1;
        });
        state.siteItem = res.data.find((item: any) => {
          return item.defaultFlag === 1;
        });
        if (state.siteItem == undefined) {
          state.siteItem = {};
        }
        if (res.data.length !== 0) {
          state.siteItem = res.data[0];
        }
      } else {
        // state.siteItem = JSON.parse(addressItem);
        //有缓存 但是没有地址 说明是返回按钮 清空地址对象
        const res = await getAddressList({ pageNumber: 100, pageSize: 1 });
        console.log(res);
        if (res.data.length == 0) {
          state.siteItem = {};
          return;
        }
        const newObj = JSON.parse(addressItem);
        (state.siteItem as Site).userName = newObj.name;
        (state.siteItem as Site).addressId = newObj.id;
        (state.siteItem as Site).defaultFlag = newObj.isDefault == true ? 1 : 0;
        (state.siteItem as Site).userPhone = newObj.tel;
        (state.siteItem as Site).detailAddress = newObj.detailAddress;
        (state.siteItem as Site).cityName = newObj.address.split("-")[0];
        (state.siteItem as Site).provinceName = newObj.address.split("-")[1];
        (state.siteItem as Site).regionName = newObj.address.split("-")[2];
      }
    };
    onMounted(async () => {
      init();
      getSiteItem();
    });

    const allCount = computed((): number => {
      const sellingPrice = state.list.map((item: Goods) => {
        return item.sellingPrice * item.goodsCount;
      });
      if (sellingPrice.length != 0) {
        return sellingPrice.reduce((n, m) => n + m);
      } else {
        return 0;
      }
    });
    const onAdd = () => {
      router.push({
        path: "/site",
      });
    };
    const popupClose = () => {
      Toast("订单生成中...");
      setTimeout(() => {
        router.replace({ path: "/order" });
      }, 2000);
    };
    const onSubmit = async () => {
      //createOrder
      // cartItemId
      if (!(state.siteItem as Site).addressId) {
        Toast("请选择收货地址!");
        return;
      }
      const cartItemId = state.list.map((item: Goods) => item.cartItemId);
      const query = {
        addressId: (state.siteItem as Site).addressId,
        cartItemIds: cartItemId,
      };
      state.orderNo = (await createOrder(query)).data;
      state.show = true;
    };
    const handPlay = async (payType: number) => {
      //state.orderNo
      state.show = false;
      await payOrder({ orderNo: state.orderNo, payType });
      Toast.success("支付成功");
      setTimeout(() => {
        router.replace({ path: "/order" });
      }, 2000);
    };
    return {
      ...toRefs(state),
      onAdd,
      onSubmit,
      allCount,
      handSeleSite,
      popupClose,
      handPlay,
    };
  },
});
</script>
<style lang="scss">
.play_title {
  font-size: 16px;
  text-align: center;
  margin-top: 20px;
}
.play_type {
  display: flex;
  flex-direction: column;
  padding: 0 20px;
  box-sizing: border-box;
  margin-top: 20px;
}
.site_list {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  .site_title {
    font-weight: bold;
    font-size: 16px;
    margin: 6px 0;
  }
}
</style>
